package com.szjlc.mybatis.sqlinterceptor.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szjlc.mybatis.sqlinterceptor.entity.Customer;
import com.szjlc.mybatis.sqlinterceptor.service.CustomerService;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 客户表(Customer)表控制层
 * @author makejava
 * @since 2022-11-28 23:30:10
 */
@Slf4j
@RestController
@RequestMapping("/customer")
public class CustomerController {

    @Resource
    private CustomerService customerService;

    /**
     * 通过主键查询单条数据
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/findById/{id}")
    public Customer selectOne(@PathVariable("id") Integer id) {
        return this.customerService.findById(id);
    }

    @GetMapping(value = "/findAll")
    public List<Customer> findAll() {
        return this.customerService.findAll();
    }

    @GetMapping(value = "/testThread/{time}")
    public void testThread(@PathVariable Integer time) {
        for (int i = 0; i < time; i++) {
            new Thread(() -> {
                double random = Math.random();
                //随机生成[a, b]之间的一个整数
                Integer id = (int) (Math.random() * (10 - 0)) + 0;
                log.info("id = {}", id);
                customerService.findById(id);
            }, "thread-" + i).start();
        }
    }

    @PostMapping(value = "/add")
    public Customer add(@RequestBody @Validated Customer customer) {
        customerService.save(customer);
        return customer;
    }

    @GetMapping(value = "/page/{currentPage}")
    public IPage<Customer> page(@PathVariable("currentPage") Integer currentPage) {
        Page<Customer> page = new Page<>(currentPage, 2);
        IPage<Customer> pageData = customerService.page(page, new QueryWrapper<Customer>().orderByDesc("customer_id"));
        return pageData;
    }

}
